
import argparse
import logging
from pathlib import Path
from core.parallel_processor import ParallelProcessor
from core.book_parser import BookParser
from core.file_manager import FileManager
from utils.chapter_word_analyzer import ChapterWordAnalyzer
from utils.logger import VocabLogger
from config.exceptions import *


def parse_arguments():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(description='电子书词汇提取工具')
    parser.add_argument('epub_path', type=str, help='EPUB文件路径')
    parser.add_argument('-c', '--chapters', nargs='+',
                        help='指定章节（支持标题或序号）')
    parser.add_argument('-t', '--threads', type=int, default=4,
                        help='线程数（默认4）')
    return parser.parse_args()

def main():
    args = parse_arguments()
    logger = VocabLogger()

    try:
        # 初始化路径
        epub_path = Path(args.epub_path)
        output_path = epub_path.with_name(
            f"{epub_path.stem}_vocab.xlsx")

        # 处理核心流程
        book_parser = BookParser(epub_path)
        book_parser.validate_and_load()
        # known_words = FileManager.load_known_words()

        # 多线程处理
        # processor = ParallelProcessor(known_words, args.threads)
        chapters = book_parser.extract_chapters()

        # 转换章节选择参数
        selected = set(args.chapters or [])
        # str(i) for i in range(1, len(chapters)+1):
        #     if 'all' in args.chapters else selected
        selected.update(selected)

        analyzer = ChapterWordAnalyzer(chapters,"data")
        analyzer.export_to_excel(f"{epub_path.stem}_vocab.xlsx")
        # results = processor.process_chapters(chapters, selected)
        # 保存结果
        # FileManager.save_vocabulary(results, output_path)
        logger.log(f"结果保存至: {output_path}")

    except BookProcessingError as e:
        logger.log(f"处理失败: {str(e)}", logging.ERROR)
    except Exception as e:
        logger.log(f"未知错误: {str(e)}", logging.CRITICAL)

if __name__ == "__main__":
    main()